package com.zjxf.shiro.session;

import com.zjxf.common.ShiroConst;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * created with IntelliJ IDEA
 * #针对不支持会话机制的请求
 * 如微信小程序等
 *
 * @author: create by limu
 * Date: 2020/7/10
 * Time：15:08
 */
public class WeChatSessionManager extends DefaultWebSessionManager {

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String authToken = WebUtils.toHttp(request).getHeader(ShiroConst.HEADER_AUTH_TOKEN_NAME);
        if (StringUtils.isEmpty(authToken)) {
            return super.getSessionId(request, response);
        } else {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, ShiroConst.REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, authToken);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return authToken;
        }
    }
}
